﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
using System.Text;
using ihongma.Common;

namespace ihongma.Web.tools
{
    /// <summary>
    /// imgdow 的摘要说明
    /// </summary>
    public class imgdow : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (HttpContext.Current.Request["InternalSysURL"] != null)
            {
                string picName = HttpContext.Current.Request.QueryString["InternalSysURL"];
                if (!String.IsNullOrEmpty(picName))
                {
                   // isimagehost(context, picName);
                    byte[] content = this.GetImageContent(picName);
                    this.WriteResponse(picName, content);
                }
            }
            if (HttpContext.Current.Request["URL"] != null)
            {
                string newspic = HttpContext.Current.Request.QueryString["URL"];
                if (!String.IsNullOrEmpty(newspic))
                {
                   // isimagehost(context, newspic);
                    byte[] content = this.GetImageContent(newspic);
                    this.newWriteResponse(newspic, content);
                }
            }
               
        }

        private void isimagehost(HttpContext context,string img)
        {
            string FileName = context.Server.MapPath("/templates/newihongma/images/logo.png");
            if (context.Request.UrlReferrer.Host != null)
            {
                if (context.Request.UrlReferrer.Host.IndexOf("ihongma.com") < 0)
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile(FileName);
                    HttpContext.Current.Response.End();
                }
              
            }
            else
            {
                context.Response.ContentType = "image/JPEG";
                context.Response.WriteFile(FileName);
                HttpContext.Current.Response.End();
            }
        }
        #region
        private byte[] GetImageContent(string picName)
        {
            string fileURL=string.Empty;
            if (picName.Contains("http"))
                fileURL = picName;
            else
                fileURL = HttpContext.Current.Server.MapPath(picName);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileURL);
            request.AllowAutoRedirect = true;

            WebProxy proxy = new WebProxy();
            proxy.BypassProxyOnLocal = true;
            proxy.UseDefaultCredentials = true;

            request.Proxy = proxy;

            WebResponse response = request.GetResponse();

            using (Stream stream = response.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Byte[] buffer = new Byte[1024];
                    int current = 0;
                    while ((current = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        ms.Write(buffer, 0, current);
                    }
                    return ms.ToArray();
                }
            }
        }

        private void WriteResponse(string picName, byte[] content)
        {

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Utils.GetRamCode() + "." + picName.Substring(picName.Length-3,3), Encoding.Default));
            HttpContext.Current.Response.AppendHeader("Content-Length", content.Length.ToString());
            HttpContext.Current.Response.BinaryWrite(content);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        private void newWriteResponse(string picName, byte[] content)
        {
         

          
            HttpContext.Current.Response.ClearContent();
           
            HttpContext.Current.Response.ContentType = "image/"+GetFormat(picName);
            HttpContext.Current.Response.BinaryWrite(GetImageContent(picName));
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 得到图片格式
        /// </summary>
        /// <param name="name">文件名称</param>
        /// <returns></returns>
        public static string GetFormat(string name)
        {
            string ext = name.Substring(name.LastIndexOf(".") + 1);
            switch (ext.ToLower())
            {
                case "jpg":
                case "jpeg":
                    return "jpg";
                case "bmp":
                    return "bmp";
                case "png":
                    return "png";
                case "gif":
                    return "gif";
                default:
                    return "jpg";
            }
        }
        #endregion
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
   
}